require 'View/UIBase/UIBase'

UICharactorInfoHeroFavor = UIBase.New(PanelNames.UICharactorInfoHeroFavor);
local this=UICharactorInfoHeroFavor
function this.Init(partnerId)
    local heroData=logicMgr.HeroManager.getHeroDatabyPartnerId(tostring(partnerId),true)
    this.heroId=heroData.partnerModelId
    UIBase.Init(this)
end

function this:OnCreate()
    self.btnInteract=self:GetChild("InteractBtn")
    self.txtInteractTip=self.btnInteract:GetChild("title")
    self.btnReward=self:GetChild("btnFavorReward")
    self.ctrlRewardState=self.btnReward:GetController("state")
    self.txtLevel=self:GetChild("FavorLevel")
    self.barExp=self:GetChild("FavorBar")
    self.txtRefNum=self.btnInteract:GetChild("tips")
    self.ctrlGift=self:GetController("gift")
    self.objContainer =self:GetChild("container")
    self.btnQuickSend=self:GetChild("btnQuick")
    self.gBound=self:GetChild("bound")
    self.gReact=self:GetChild("react")
    self.btnBG=self:GetChild("bg")
    self.interactionInfo=logicMgr.HeroFavorManager.getInteractionInfo()
    self:addEvent();
    self.btnBG.visible=false
end
function this:OnEnable()
    self.objGifts={}
    self.giftDatas=logicMgr.ItemManager.getConstFavorItemDatas()
    for i=1,#self.giftDatas do
        local temp=UIPackage.CreateObject("CharactorUI", "gift");
        temp.name="gift"..i
        --temp.pivot=Vector2(0.5,0.5)
        self:SetItemPosition(temp,i)
        self.objContainer:AddChild(temp)
        table.insert(self.objGifts,temp)
        self:SetDragItem(temp,i)
    end
    self.isMoving={}
    self:Refresh()
    UIRedDots.addViewListen(PanelNames.UICharactorInfoHeroFavor, "UICharactorInfoHeroFavor" .. self.btnInteract.gameObjectName, self.btnInteract, Config.RedDotsType.HeroInteractionPoint, self.heroData.partnerId);
    UIRedDots.addViewListen(PanelNames.UICharactorInfoHeroFavor, "UICharactorInfoHeroFavor" .. self.btnReward.gameObjectName, self.btnReward, Config.RedDotsType.HeroInteractionReward, self.heroData.partnerId);

end


function this:OnDisable()
    if not table.isNullOrEmpty(self.objGifts)  then
        for i = 1, #self.objGifts do
            self.objGifts[i]:Dispose();
        end
    end
    self.objGifts = {};
    UIRedDots.removeViewEvent(PanelNames.UICharactorInfoHeroFavor)
end

function this:OnDestroy()

end
-------------------------------function--------------------------------------
function this:OnClickClose()

end
function this:addEvent()
    self:RegisterOnClick(self.btnInteract,self.OnClickBtnInteract)
    self:RegisterOnClick(self.btnQuickSend,self.OnClickBtnQuickSend)
    self:RegisterEvent(Config.EventType.Fresh_HeroInteraction,self.Refresh)
end



function this:Refresh()
    self.heroData=logicMgr.HeroManager.getHeroDatabyModelId(this.heroId,true)
    --local txtRefTips=self.btnReward:GetChild("tips")
    self.txtLevel.text="等级"..tostring(self.heroData.favorLv)
    local allNum=self.interactionInfo[1].f_FrequencyCo
    self.txtRefNum.text=string.format(getLanguage("HeroFavorText1"),tostring(allNum-logicMgr.HeroManager.getHeroInteractionNum()))

    local rewardData=logicMgr.HeroFavorManager.getRewardData(self.heroId)
    if self.heroData.favorLv==10 then
        self.barExp.value=100
    else
        local exp=rewardData[self.heroData.favorLv+1].f_FavorExp-rewardData[self.heroData.favorLv].f_FavorExp
        self.barExp.value=(self.heroData.favorExp-rewardData[self.heroData.favorLv].f_FavorExp)/exp*100
    end
    self:UpdateRewardState()
    self:UpdateGift()
    self:RefreshInteractButttonTip()
end
function this:SetItemPosition(item,index)
    local delta=200
    local single=176
    local offset=delta-single
    local num=#self.giftDatas
    if num<=0 then
        return
    end
    local startX=-1*(0.5*(num-1)*offset+0.5*(num)*single)
    item:SetPosition(startX+(index-1)*delta,0,0)
    --item:SetPosition(0,0,0)
end
local function CalculateGift(heroData,giftDatas)
    local gifts={}
    local rewardData=logicMgr.HeroFavorManager.getRewardData(heroData.partnerModelId)[10]
    if table.isNullOrEmpty(rewardData)then
        printError("没找到好感度奖励数据"..heroData.itemModelId)
    else
        local topExp=rewardData.f_FavorExp
        local offsetExp=topExp-heroData.favorExp
        for i,v in ipairs(giftDatas)do
            local num=v.num
            while(num>0 and offsetExp>0)do
                local exp=decodeJsonStrToTabel(v.itemFunction)[2]
                offsetExp=offsetExp-exp
                num=num-1
                if gifts[v.itemId]==nil then
                    gifts[v.itemId]=1
                else
                    gifts[v.itemId]=gifts[v.itemId]+1
                end
            end
            if offsetExp<=0 then
                break
            end
        end
    end
    local temp={}
    for i,v in pairs(gifts)do
        table.insert(temp,i)
        table.insert(temp,v)
    end
    return temp
end
function this:OnClickBtnQuickSend()
    local gifts=CalculateGift(self.heroData,self.giftDatas)
    if not table.isNullOrEmpty(gifts)then
        partnerHandler.ReqPartnerInteractGive(self.heroData.partnerId,gifts)
    else
        UISysTips.AddMsg(getLanguage("HeroFavorItemTips1"));
    end
end
function this:UpdateGift()
    if self.heroData.favorLv>=10 then
        self.ctrlGift.selectedIndex=0
    else
        self.ctrlGift.selectedIndex=1
        self.giftDatas=logicMgr.ItemManager.getConstFavorItemDatas()
        for i,v in ipairs(self.giftDatas)do
            v.num=logicMgr.ItemManager.getBagNumByTableID(v.itemModelId)
            v.itemId=logicMgr.ItemManager.getItemIdByModelId(v.itemModelId) or 0
        end
        local itemCtrl=CtrlManager.GetCtrl(PanelNames.Item)
        for i,v in ipairs(self.giftDatas)do
            local item= self.objGifts[i]
            itemCtrl.initData(item:GetChild("item"),v)
            item:GetChild("item").onClick:Clear()
            item.draggable=true
            if v.num==0 then
                item.draggable=false
                item.grayed=true
                item.onClick:Clear()
                item.onClick:Add(function()
                    --UISysTips.AddMsg(string.format("%s不足",v.name))
                end)
            else
                item.draggable=true
                item.onClick:Clear()
                item.onClick:Add(function()
                    showUI(PanelNames.UIBagItemInfo, v);
                end)
                item.grayed=false
            end
        end
    end
end

function this:RefreshInteractButttonTip()
    local function GetInteractionData(interactId)
        local interactData = {}
        for i,v in pairs(self.heroData.interactInfos) do
            if v.id==interactId then
                interactData=v
                break
            end
        end
        return interactData
    end
    local data = self.interactionInfo[1]
    local interactData=GetInteractionData(data.f_InteractionId) or {}
    if table.isNullOrEmpty(interactData)then
        interactData.times=0
    end
    local isFinish=false
    if interactData.times>=data.f_Frequency then
        isFinish=true
    end
    if isFinish then
        self.txtInteractTip.text = "今日已互动"
    else
        self.txtInteractTip.text = "互动"
    end
end

function this:SetDragItem(item,index)
    if item.dragBounds==nil then
        item.dragBounds = UnityEngine.Rect.New(self.gBound.x, self.gBound.y, self.gBound.actualWidth, self.gBound.actualHeight);
    end
    item.onTouchBegin:Add(function()
        self:onDragStartFunc(item,index)
    end);
    item.onTouchMove:Add(function()
        self:onDragMoveFunc(item,index)
    end);
    item.onTouchEnd:Add(function()
        self:onDragEndFunc(item,index)
    end);
end
function this:ClearDragItem(item)
end
function this:onDragStartFunc(item,index)
    self.isMoving[index]=true
    self.btnBG.visible=true
    if self.giftDatas[index].num==0 then
        UISysTips.AddMsg(string.format("%s不足",self.giftDatas[index].name))
    else
        item:GetChild("item"):GetController("gift").selectedIndex=1
    end
    --print("开始拖动"..item.name.."draggable:"..tostring(item.draggable))
end

function this:onDragMoveFunc(item,index)
    --print("拖动"..item.name.."draggable:"..tostring(item.draggable) )
end

function this:onDragEndFunc(item,index)
    item:GetChild("item"):GetController("gift").selectedIndex=0
    if self.isMoving[index]  then
        self.btnBG.visible=true

        self.isMoving[index]=false
        --print("结束拖动"..item.name.."draggable:"..tostring(item.draggable) )
        local itemData=self.giftDatas[index]
        if not isIntersectWithGlobal(self.gReact,self.fguiObj,item,self.objContainer)then
            --print("拖动结束外面"..itemData.itemModelId)
            partnerHandler.ReqPartnerInteractGive(self.heroData.partnerId,{itemData.itemId,1})
        else
            --print("拖动结束里面"..itemData.itemModelId)
        end
    end
    self:SetItemPosition(item,index)

end

function this:UpdateRewardState()
    local rewardData=logicMgr.HeroFavorManager.getRewardData(self.heroId)
    local flag=false
    local rewardId=0
    for i=self.heroData.favorRewardGetLv+1,self.heroData.favorLv do
        if rewardData[i].f_RewardType==3 then
            flag=true
            rewardId=rewardData[i].f_FavorId
        end
    end
    if flag then
        self.ctrlRewardState.selectedIndex=1
    else
        self.ctrlRewardState.selectedIndex=0
    end
    self.btnReward.onClick:Clear()
    self.btnReward.onClick:Add(function()
        if flag then
            partnerHandler.ReqPartnerFavorRewardGet(self.heroData.partnerId,rewardId)
        else
            showUI(PanelNames.UIFavorAward,this.heroId)
        end
    end)
end

--[[
有互动，且有次数。则点击按钮直接进剧情
无互动，且有次数，则点击出现现有弹窗
无互动，无次数，则点击出现现有弹窗
有互动，但无次数，则点击出现现有弹窗
--]]
function this:OnClickBtnInteract()
    --showUI(PanelNames.UICharactorInteraction,this.heroId)
    local function GetInteractionData(interactId)
        local interactData = {}
        for i,v in pairs(self.heroData.interactInfos) do
            if v.id==interactId then
                interactData=v
                break
            end
        end
        return interactData
    end
    local data = self.interactionInfo[1]
    local interactData=GetInteractionData(data.f_InteractionId) or {}
    if table.isNullOrEmpty(interactData)then
        interactData.times=0
    end
    local isFinish=false
    if interactData.times>=data.f_Frequency then
        isFinish=true
    end
    local num=logicMgr.HeroManager.getHeroInteractionNum()
    if isFinish then
        showUI(PanelNames.UICharactorInteraction,this.heroId)
    elseif data.f_FrequencyType==1 and num>=data.f_FrequencyCo then
        showUI(PanelNames.UICharactorInteraction,this.heroId)
    else
        self.roleData = dataTable.getRow("t_roleinfo",this.heroId)
        logicMgr.StoryMgr.ShowStoryById(self.roleData.f_RoleInteractionStory,EnumConst.StoryShowType.review)
        local info={}
        info.partnerId=self.heroData.partnerId
        info.lastLevel=self.heroData.favorLv
        info.lastExp=self.heroData.favorExp
        partnerHandler.setInteractionSaveData({info},self.interactionInfo[1].f_InteractionId)
    end
end

return this;